<template>
	<view>
		<ncDusease ref="checkRef" titleName="病害审核" compoType="approval"  v-model="detailObj.mileage"
			:subTitleName="detailObj.lineSiteSectionName || ''" :lineSiteSectionType="detailObj.lineSiteSectionType || ''" @passSubmit="passSubmit"></ncDusease>
	</view>
</template>

<script>
	import ncDusease from '../../common/ncDusease.vue'
	import { diseaseOrderReview, diseaseOrderGetDetails } from "@/api/engineeringMaintenance/engineeringMaintenance.js"
	import { uploadFile } from '@/utils/request'
	import { getToken } from '@/utils/auth.js'
	import mixins from '@/utils/mixins.js'
	import { getPicture, deleteImg, doc_deleteAttachs } from '@/api/doc.js'
	import { urlTobase64, uploadImageFromBase64} from '@/utils/imageOperation.js'
	export default {
		name: 'newly',
		components: {
			ncDusease
		},
		mixins: [mixins],
		data() {
			return {
				detailObj: {},
				mileage:'',
				requestStatus:false,
				isRequest:false
			}
		},
		methods: {
			passSubmit(obj, booleanValue) {
				this.$set(obj, 'isAdopt', booleanValue)
				console.log(obj, booleanValue, '父组件值')
				// return
				if(obj && obj.videoFileList && obj.videoFileList.length > 0){
					const taskArr = obj.videoFileList.filter(it => it.uploadStatus)
					if(taskArr.length > 0) {
						uni.showToast({
							title:'视频上传中,请稍等',
							icon:'none',
							mask:true
						})
						return
					}
				}
				const hasRing = !!(obj.startNumber && obj.endNumber)
				const hasMile = !!(obj.startMileageFront && obj.startMileageAfter && obj.endMileageFront && obj
					.endMileageAfter)
				const hasOther = !!(obj.others)
				const hasStationLocation = !!(obj.stationLocation)
				console.log(hasRing,hasMile,hasOther,hasStationLocation);
				if (!hasRing && !hasMile && !hasOther && !hasStationLocation) {
					if (obj.lineSiteSectionType == 'qj') {
						uni.showToast({
							title: '里程、环号、其他中必须填写一个!',
							icon: 'none',
						})
					} else if (obj.lineSiteSectionType == 'cz') {
						uni.showToast({
							title: '车站位置和其他中必须填写一个!',
							icon: 'none',
						})
					} else {
						uni.showToast({
							title: '位置为必填项!',
							icon: 'none',
						})
					}
					return
				}
				if (!hasRing && (obj.startNumber || obj.endNumber)) {
						return uni.showToast({
							title:'请检查数据格式',
							icon:'none'
						})
				}
				if (!hasMile && (obj.startMileageFront || obj.startMileageAfter || obj.endMileageFront || obj.endMileageAfter)) {
						return uni.showToast({
							title:'请检查数据格式',
							icon:'none'
						})
				}
                if(this.requestStatus) return
                this.requestStatus = true
				// 删除视频记录的视频id
				let arr = [...obj.removeFileSet] || []
				if(arr.length) {
					doc_deleteAttachs(arr)
				}
				diseaseOrderReview({
					...obj
				}).then(res => {
					console.log(res, '通过')
					this.isRequest = true
					if (res.success) {
						uni.showToast({
							title: res.message,
							icon: 'none',
							mask: true,
						})
						setTimeout(() => {
							uni.navigateBack()
							this.requestStatus = false
							this.$emit('refreshList')
						}, 1600)
					}else {
						this.requestStatus = false
					}
				})
			},
			/**
			 * 获取到docId中的图片并且拼成网络路径格式
			 * @param {Number} docId
			 * @return {String} //拼好的网络路径格式
			 */
			async getItemImage(docId) {
				console.log('传进来的文档id', docId, this.$config.IMG_FILE_URL);
				return await new Promise((resolve, reject) => {
					getPicture({
						docId
					}).then(res => {
						let imgResult = res.result.filter(item => item.contentType.substring(0, item
							.contentType.indexOf("/")) === 'image')
						resolve(imgResult.map(it => ({
							url: this.$config.IMG_FILE_URL + it.fileName,
							id: it.id
						})));
					}).catch(err => reject(err))
				})
			},
			async getVideoList(docId) {
				console.log('传进来的文档id', docId, this.$config.IMG_FILE_URL);
				return await new Promise((resolve, reject) => {
					getPicture({
						docId
					}).then(res => {
						let videoResult = res.result.filter(item => item.contentType.substring(0, item
							.contentType.indexOf("/")) === 'video')
						resolve(videoResult.map(it => ({
							url: this.$config.VIDEO_URL + it.fileName,
							id: it.id
						})));
					}).catch(err => reject(err))
				})
			}
		},
		onLoad(params) {
			if (params && params.id) {
				// this.mileage = params.type
				console.log(this.mileage,'----')
				diseaseOrderGetDetails({
					id: params.id
				}).then(async res => {
					console.log(res, 'iii')
					if (res.success) {
						this.detailObj = res.result
						this.$set(this.detailObj,'diseaseGrade',res.result.diseaseGradeName || '')
						if (res.result.docId) {
							let a = await this.getItemImage(res.result.docId)
							this.$set(this.detailObj, 'fileListImg', a)
							this.detailObj.sourceImgs = JSON.parse(JSON.stringify(a))
						}else {
							this.$set(this.detailObj, 'fileListImg', [])
						}
						if (res.result.videoDocId) {
							let video = await this.getVideoList(res.result.videoDocId) || []
							this.$set(this.detailObj, 'videoFileList', video)
							this.detailObj.sourceVideos = JSON.parse(JSON.stringify(video))
						}else {
							this.$set(this.detailObj, 'videoFileList', [])
						}
					}
					this.$set(this.detailObj, 'updateIds', [])
					this.$set(this.detailObj, 'updateVideoIds', [])
					this.detailObj.removeFileSet = new Set()
					this.$refs.checkRef.changeBefore = this.detailObj
				})
			}
		},
		async beforeDestroy() {
			if(!this.isRequest) {
				console.error('销毁钩子函数',this.detailObj)
				// 新加图片后没有点击操作按钮直接退出 需要删除新加的id
				let needDelIds = [], needDelIds2 = []
				if(this.detailObj.updateIds.length) {
					let ids = this.detailObj.sourceImgs.map(i => i.id)
					needDelIds = this.getDifference(ids, this.detailObj.updateIds)
				}
				// 删除视频
				if(this.detailObj.updateVideoIds.length) {
					let ids = this.detailObj.sourceVideos.map(i => i.id)
					needDelIds2 = this.getDifference(ids, this.detailObj.updateVideoIds)
				}
				let allIds = [].concat(needDelIds, needDelIds2)
				if(allIds.length) {
					await doc_deleteAttachs(allIds)
				}
				// 找出删除的数据 原数据和现在的数组对比,并上传
				let result = this.getArrDifSameValue(this.detailObj.fileListImg, this.detailObj.sourceImgs || [])
				console.error(result)
				if(result.length) {
					let base64List = []
					let dataList = []
					for(let it of result) {
						const base64_img = await urlTobase64(it.url)
						base64List.push(base64_img.split(",")[1])
					}
					// 水印数据
					let formData = {}
					//区间/站点
					formData.name = this.detailObj.lineSiteSectionName
					//里程
					const distance = this.getContent2(this.detailObj)
					//环号
					const startRing = this.detailObj.startNumber || ''
					const endRing = this.detailObj.endNumber || ''
					const others = this.detailObj.others || ''
					const timeClock = this.detailObj.clockwisePosition || ''
					formData.ring =
						`${distance}${distance && startRing ? ',' : ''}${startRing}${startRing && endRing ? '~' : '' }${endRing}${(distance && others)||(endRing && others) ? ',' : ''}${others}${(distance && timeClock)  ||  (startRing && endRing && timeClock) || (others&&timeClock)  ? ',' : ''}${timeClock}`
					//现状
					formData.status = this.detailObj.diseaseStatus || ''
					formData.dateTime = this.getDate2(new Date)
					let response = await uploadImageFromBase64({
						dataList:[formData.name, formData.ring, formData.status, formData.dateTime],
						docId:this.detailObj.docId,
						base64List
					})
					console.error(response, '结果')
				}
				
				//找出删除的视频并且重新上传
				// let result2 = this.getArrDifSameValue(this.detailObj.videoFileList, this.detailObj.sourceVideos || [])
				// console.log(result2, '视频文件')
				// if(result2.length) {
				// 	for(let item of result2) {
				// 		uni.downloadFile({
				// 			url: item.url,
				// 			success: async (res) => {
				// 				if (res.statusCode === 200) {
				// 					console.error(res,'下载成功');
				// 					// #ifdef MP-WEIXIN
				// 					const uploadResq = {
				// 						url: "rest/doc/uploadDoc",
				// 						formData:{ docId:this.detailObj.videoDocId, },
				// 						name: 'attach',
				// 						filePath: res.tempFilePath,
				// 						isOffline: true
				// 					}
				// 					// #endif
									
				// 					// #ifdef APP-PLUS || H5
				// 					const uploadResq = {
				// 						url: "rest/doc/uploadDoc",
				// 						formData:{ docId:this.detailObj.videoDocId, },
				// 						files: [{
				// 							name: "attach",
				// 							uri: res.tempFilePath
				// 						}],
				// 						isOffline: true
				// 					}
				// 					// #endif
				// 					let data = await uploadFile(uploadResq)
				// 					console.error(data, '165行上传视频')
				// 				}
				// 			}
				// 		});
				// 	}
				// }
			}
			
		},
	}
</script>

<style lang="scss" scoped>

</style>
